const express = require('express');
const auth = require('../../middleware/auth');

const router = express.Router();

// 模拟停车位数据
let parkingSpacesData = [
  {
    id: '1',
    spotNumber: 'A001',
    zone: 'A',
    floor: -1,
    status: 'occupied',
    hourlyRate: 5,
    isVIP: false,
    vehicleInfo: {
      plateNumber: '京A12345',
      vehicleType: '轿车',
      ownerName: '张三',
      checkInTime: '2024-01-15 08:30:00',
      phone: '13800138000'
    }
  },
  {
    id: '2',
    spotNumber: 'A002',
    zone: 'A',
    floor: -1,
    status: 'available',
    hourlyRate: 5,
    isVIP: false
  },
  {
    id: '3',
    spotNumber: 'B001',
    zone: 'B',
    floor: -2,
    status: 'reserved',
    hourlyRate: 8,
    isVIP: true,
    vehicleInfo: {
      plateNumber: '京B67890',
      vehicleType: 'SUV',
      ownerName: '李四',
      reservationTime: '2024-01-15 14:00:00',
      phone: '13800138001'
    }
  },
  {
    id: '4',
    spotNumber: 'C001',
    zone: 'C',
    floor: 1,
    status: 'maintenance',
    hourlyRate: 5,
    isVIP: false
  },
  {
    id: '5',
    spotNumber: 'D001',
    zone: 'D',
    floor: 2,
    status: 'available',
    hourlyRate: 6,
    isVIP: false
  }
];

// 获取停车位列表
router.get('/spaces', auth, async (req, res) => {
  try {
    const { zone, status, floor } = req.query;
    let filteredSpaces = parkingSpacesData;
    
    // 根据查询参数过滤
    if (zone) {
      filteredSpaces = filteredSpaces.filter(space => space.zone === zone);
    }
    if (status) {
      filteredSpaces = filteredSpaces.filter(space => space.status === status);
    }
    if (floor) {
      filteredSpaces = filteredSpaces.filter(space => space.floor === parseInt(floor));
    }
    
    res.json({
      success: true,
      data: filteredSpaces,
      total: filteredSpaces.length
    });
  } catch (error) {
    console.error('Get parking spaces error:', error);
    res.status(500).json({ error: '获取停车位列表失败' });
  }
});

// 获取单个停车位信息
router.get('/spaces/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const space = parkingSpacesData.find(s => s.id === id);
    
    if (!space) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    res.json({
      success: true,
      data: space
    });
  } catch (error) {
    console.error('Get parking space error:', error);
    res.status(500).json({ error: '获取停车位信息失败' });
  }
});

// 创建停车位
router.post('/spaces', auth, async (req, res) => {
  try {
    const { spotNumber, zone, floor, hourlyRate, isVIP } = req.body;
    
    // 验证必填字段
    if (!spotNumber || !zone || floor === undefined || !hourlyRate) {
      return res.status(400).json({ error: '请填写所有必填字段' });
    }
    
    // 检查车位号是否已存在
    const existingSpace = parkingSpacesData.find(s => s.spotNumber === spotNumber);
    if (existingSpace) {
      return res.status(400).json({ error: '车位号已存在' });
    }
    
    const newSpace = {
      id: Date.now().toString(),
      spotNumber,
      zone,
      floor: parseInt(floor),
      hourlyRate: parseFloat(hourlyRate),
      isVIP: Boolean(isVIP),
      status: 'available',
      createdAt: new Date().toLocaleString('zh-CN')
    };
    
    parkingSpacesData.push(newSpace);
    
    res.status(201).json({
      success: true,
      data: newSpace,
      message: '停车位创建成功'
    });
  } catch (error) {
    console.error('Create parking space error:', error);
    res.status(500).json({ error: '创建停车位失败' });
  }
});

// 更新停车位
router.put('/spaces/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { spotNumber, zone, floor, hourlyRate, isVIP, status } = req.body;
    
    const spaceIndex = parkingSpacesData.findIndex(s => s.id === id);
    if (spaceIndex === -1) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    // 检查车位号是否被其他车位使用
    if (spotNumber) {
      const existingSpace = parkingSpacesData.find(s => s.spotNumber === spotNumber && s.id !== id);
      if (existingSpace) {
        return res.status(400).json({ error: '车位号已被其他车位使用' });
      }
    }
    
    parkingSpacesData[spaceIndex] = {
      ...parkingSpacesData[spaceIndex],
      spotNumber: spotNumber || parkingSpacesData[spaceIndex].spotNumber,
      zone: zone || parkingSpacesData[spaceIndex].zone,
      floor: floor !== undefined ? parseInt(floor) : parkingSpacesData[spaceIndex].floor,
      hourlyRate: hourlyRate !== undefined ? parseFloat(hourlyRate) : parkingSpacesData[spaceIndex].hourlyRate,
      isVIP: isVIP !== undefined ? Boolean(isVIP) : parkingSpacesData[spaceIndex].isVIP,
      status: status || parkingSpacesData[spaceIndex].status,
      updatedAt: new Date().toLocaleString('zh-CN')
    };
    
    res.json({
      success: true,
      data: parkingSpacesData[spaceIndex],
      message: '停车位更新成功'
    });
  } catch (error) {
    console.error('Update parking space error:', error);
    res.status(500).json({ error: '更新停车位失败' });
  }
});

// 删除停车位
router.delete('/spaces/:id', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const spaceIndex = parkingSpacesData.findIndex(s => s.id === id);
    if (spaceIndex === -1) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    // 检查车位是否被占用
    if (parkingSpacesData[spaceIndex].status === 'occupied') {
      return res.status(400).json({ error: '车位被占用，无法删除' });
    }
    
    const deletedSpace = parkingSpacesData.splice(spaceIndex, 1)[0];
    
    res.json({
      success: true,
      data: deletedSpace,
      message: '停车位删除成功'
    });
  } catch (error) {
    console.error('Delete parking space error:', error);
    res.status(500).json({ error: '删除停车位失败' });
  }
});

// 预约停车位
router.post('/spaces/:id/reserve', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { plateNumber, ownerName, vehicleType, phone } = req.body;
    
    const spaceIndex = parkingSpacesData.findIndex(s => s.id === id);
    if (spaceIndex === -1) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    if (parkingSpacesData[spaceIndex].status !== 'available') {
      return res.status(400).json({ error: '停车位不可用' });
    }
    
    // 验证必填字段
    if (!plateNumber || !ownerName || !vehicleType || !phone) {
      return res.status(400).json({ error: '请填写所有必填字段' });
    }
    
    parkingSpacesData[spaceIndex].status = 'reserved';
    parkingSpacesData[spaceIndex].vehicleInfo = {
      plateNumber,
      ownerName,
      vehicleType,
      phone,
      reservationTime: new Date().toLocaleString('zh-CN')
    };
    
    console.log(`Parking space ${id} reserved by ${ownerName} (${plateNumber})`);
    
    res.json({
      success: true,
      data: parkingSpacesData[spaceIndex],
      message: '预约成功'
    });
  } catch (error) {
    console.error('Reserve parking space error:', error);
    res.status(500).json({ error: '预约失败' });
  }
});

// 车辆入场
router.post('/spaces/:id/checkin', auth, async (req, res) => {
  try {
    const { id } = req.params;
    const { plateNumber, ownerName, vehicleType, phone } = req.body;
    
    const spaceIndex = parkingSpacesData.findIndex(s => s.id === id);
    if (spaceIndex === -1) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    if (parkingSpacesData[spaceIndex].status === 'occupied') {
      return res.status(400).json({ error: '停车位已被占用' });
    }
    
    parkingSpacesData[spaceIndex].status = 'occupied';
    parkingSpacesData[spaceIndex].vehicleInfo = {
      plateNumber,
      ownerName,
      vehicleType,
      phone,
      checkInTime: new Date().toLocaleString('zh-CN')
    };
    
    res.json({
      success: true,
      data: parkingSpacesData[spaceIndex],
      message: '入场成功'
    });
  } catch (error) {
    console.error('Check in parking space error:', error);
    res.status(500).json({ error: '入场失败' });
  }
});

// 车辆离场
router.post('/spaces/:id/checkout', auth, async (req, res) => {
  try {
    const { id } = req.params;
    
    const spaceIndex = parkingSpacesData.findIndex(s => s.id === id);
    if (spaceIndex === -1) {
      return res.status(404).json({ error: '停车位不存在' });
    }
    
    if (parkingSpacesData[spaceIndex].status !== 'occupied') {
      return res.status(400).json({ error: '停车位未被占用' });
    }
    
    const vehicleInfo = parkingSpacesData[spaceIndex].vehicleInfo;
    const checkInTime = new Date(vehicleInfo.checkInTime);
    const checkOutTime = new Date();
    const duration = Math.ceil((checkOutTime - checkInTime) / (1000 * 60 * 60)); // 小时
    const fee = duration * parkingSpacesData[spaceIndex].hourlyRate;
    
    parkingSpacesData[spaceIndex].status = 'available';
    parkingSpacesData[spaceIndex].vehicleInfo = {
      ...vehicleInfo,
      checkOutTime: checkOutTime.toLocaleString('zh-CN'),
      duration,
      fee
    };
    
    // 清空车辆信息（保留历史记录）
    setTimeout(() => {
      delete parkingSpacesData[spaceIndex].vehicleInfo;
    }, 5000);
    
    res.json({
      success: true,
      data: {
        space: parkingSpacesData[spaceIndex],
        fee,
        duration
      },
      message: '离场成功'
    });
  } catch (error) {
    console.error('Check out parking space error:', error);
    res.status(500).json({ error: '离场失败' });
  }
});

// 获取停车统计
router.get('/stats', auth, async (req, res) => {
  try {
    const total = parkingSpacesData.length;
    const available = parkingSpacesData.filter(s => s.status === 'available').length;
    const occupied = parkingSpacesData.filter(s => s.status === 'occupied').length;
    const reserved = parkingSpacesData.filter(s => s.status === 'reserved').length;
    const maintenance = parkingSpacesData.filter(s => s.status === 'maintenance').length;
    
    const zoneStats = {};
    parkingSpacesData.forEach(space => {
      if (!zoneStats[space.zone]) {
        zoneStats[space.zone] = { total: 0, available: 0, occupied: 0 };
      }
      zoneStats[space.zone].total++;
      if (space.status === 'available') zoneStats[space.zone].available++;
      if (space.status === 'occupied') zoneStats[space.zone].occupied++;
    });
    
    res.json({
      success: true,
      data: {
        total,
        available,
        occupied,
        reserved,
        maintenance,
        occupancyRate: total > 0 ? ((occupied / total) * 100).toFixed(1) : 0,
        zoneStats
      }
    });
  } catch (error) {
    console.error('Get parking stats error:', error);
    res.status(500).json({ error: '获取停车统计失败' });
  }
});

module.exports = router;
